package com.web.music.impl;

import java.util.Collection;

import javax.persistence.NoResultException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.web.music.interfaces.SecurityController;
import com.web.music.model.SecuredEntity;
import com.web.music.interfaces.UserService;
import com.web.music.model.User;

public class SecurityControllerImpl implements SecurityController {
	
	protected static final String USER_ATTRIBUTE = "_user";
	
	private UserService userService;
	
	public boolean doLogin(HttpServletRequest request, String login, String password) {
		User user = null;
		try {
			user = userService.getByLoginPassword(login, password);
		} catch (NoResultException e) {
			//user not found
		}
		HttpSession session = request.getSession();
		session.setAttribute(USER_ATTRIBUTE, user);
		return user != null;
	}
	
	public void doLogout(HttpServletRequest request) {
		HttpSession session = request.getSession();
		session.removeAttribute(USER_ATTRIBUTE);
	}
	
	public User getSessionUser(HttpServletRequest request) {
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(USER_ATTRIBUTE);
		if (user != null) {
			user = userService.getById(user.getId());
		}
		return user;
	}
	
	public void updateSecurityStatus(HttpServletRequest request, Collection<? extends SecuredEntity> list) {
		User user = getSessionUser(request);
		for (SecuredEntity entity : list) {
			entity.setUpdateGranted(SecurityHelper.isUpdateGranted(entity, user));
		}
	}
	
	public void updateSecurityStatus(HttpServletRequest request, SecuredEntity entity) {
		User user = getSessionUser(request);
		entity.setUpdateGranted(SecurityHelper.isUpdateGranted(entity, user));
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
}
